package de.koller.worlders.gameplay;

import de.koller.oceanFramework.tree.Child;
import de.koller.oceanFramework.util.MIn;
import de.koller.oceanFramework.util.MOut;
import de.koller.worlders.WSea;
import de.koller.worlders.engine.entity.zone.Spawner;
import de.koller.worlders.gameplay.progress.HighLand;
import de.koller.worlders.gameplay.progress.JumpProgress;
import de.koller.worlders.gameplay.progress.LivingMobs;
import java.util.HashSet;
import java.util.Set;

public class Progress extends WSea {
	
	private final Set<ProgressUnit> units = new HashSet<>();
	
	@Child private final JumpProgress jumpProgress = new JumpProgress( 1, 4, 1 );
	
	@Child private final HighLand highLand = new HighLand( 2, 3, 2 );
	@Child private final LivingMobs livingMobs = new LivingMobs( 3, 5, 2 );

	@Override
	protected void init() {
		super.init();
		
//		jumpProgress.setAvailable( true );
	}

	@Override
	protected void postChildInit() {
		super.postChildInit();
		
		wroot.getGui().getAchGet().setIgnorShow( true );
		load();
		wroot.getGui().getAchGet().setIgnorShow( false );
	}
	
	private void achieve( ProgressUnit pu ) {
		if( pu == jumpProgress ) {
			highLand.setAvailable( true );
			livingMobs.setAvailable( true );
			
			if( !jumpProgress.isAchieved() )
				wroot.gamePlayer.playerPoints.getBuildableTiles().addAllowed( Spawner.GEN_ID, 0, 1 );
		}
		
		pu.achieve();
	}
	
	private void load() {
		MIn min = new MIn( wroot.getUser().getUserpath() + "progress.2mp" );
		int in = min.readInt( 1 )[0];
		while( in != 0 ) {
			for( ProgressUnit pu : units ) {
				if( in == pu.getId() )
					achieve( pu );
			}
			
			in = min.read( 1 )[0];
		}
		min.close();
	}
	
	public Set<ProgressUnit> getUnits() {
		return units;
	}
	
	public void pointProgress() {
		int p = wroot.gamePlayer.playerPoints.getPoints();
		int t = wroot.gamePlayer.playerPoints.getTryTime();
		
		if( jumpProgress.isSolved( p, t ) ) this.achieve( jumpProgress );
	}
	
	public boolean buildModusAchi() {
		return jumpProgress.isAchieved();
	}
	
	public void save() {
		MOut mout = new MOut( wroot.getUser().getUserpath() + "progress.2mp" );
		for( ProgressUnit pu : units )
			if( pu.isAchieved() )
				mout.writeInt( pu.getId() );
		mout.close();
		
		System.out.println( "Progress saved" );
	}
	
}
